<template>
  <h1>UsersList</h1>
  <el-card style="width: 100%;">
    <h1>用户列表</h1>
    <!--  搜索筛选表单 -->
    <el-form :model="searchForm" :inline="true">
      <el-form-item label="姓名搜索：">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="电话搜索：">
        <el-input v-model="searchForm.phone" placeholder="请输入电话号码" clearable></el-input>
      </el-form-item>
      <el-form-item label="日期搜索：">
        <el-date-picker v-model="timeRanges" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="onSearch">搜索</el-button>
        <el-button type="primary" icon="refresh" plain @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!--  用户列表展示 -->
    <el-table :data="filteredUsersTable" border style="width: 100%">
      <el-table-column type="selection" label="#" width="50" align="center"></el-table-column>
      <el-table-column prop="avatar" label="头像" align="center">
        <template #default="{ row }">
          <img :src="row.portrait || defaultAvatar" alt="头像" class="user-avatar"/>
        </template>
      </el-table-column>
      <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop"
                       :label="column.label" :width="column.width" :align="column.align">
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-switch v-model="row.status" class="mb-2"
                     active-value="ENABLE"
                     inactive-value="DISABLE"
                     @change="onStatusChange($event, row.id)"/>
          <span v-if="row.status === 'ENABLE'">启用</span>
          <span v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="{ row }">
          <el-button type="primary" plain @click="handlerAllocRole(row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页器 -->
    <el-pagination class="mt-20"
                   @size-change="onPageSizeChange"
                   @current-change="onCurrentPageChange"
                   :current-page="currentPage"
                   :page-sizes="[10, 20, 30, 40]"
                   :page-size="pageSize" :total="total"
                   layout="total, prev, pager, next, sizes, jumper"
    />

    <!--  弹窗组件-->
<!--    <el-dialog v-model="dialogVisible" title="分配角色" width="500">-->
<!--      <AllocRole />-->
<!--    </el-dialog>-->
    <AllocRole ref="allocRole" />

  </el-card>

</template>

<script setup>
import {onMounted, ref} from 'vue'
import {reqDisableUserStatus, reqEnableUserStatus, reqUserPages} from '@/api/userinfo.js'
import {ElMessage} from "element-plus";
import AllocRole from "@/views/users/components/AllocRole.vue";

onMounted(() => {
  getUsersList()
})

const dialogVisible = ref(false)
// 搜索表单
const searchForm = ref({
  name: '',
  phone: '',
})

// 时间范围
const timeRanges = ref([])

// 存储用户列表数据
const usersTable = ref([])

// 新增用于存储过滤后的用户数据
const filteredUsersTable = ref([])
// 默认头像的路径
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
// 表格列
const columns = [
  {prop: 'id', label: '用户ID', width: 100, align: 'center'},
  {prop: 'name', label: '用户姓名', align: 'center'},
  {prop: 'phone', label: '用户电话', align: 'center'},
  {prop: 'createTime', label: '创建时间', align: 'center'},
  {prop: 'status', label: '用户状态', align: 'center'},
]

// 输入之后进行搜索
const onSearch = () => {
  // 过滤用户列表
  const { name = '', phone = '' } = searchForm.value || {};
  const [start = null, end = null] = timeRanges.value || [];
  // 检查 usersTable.value 是否有效
  // if (!usersTable.value || !Array.isArray(usersTable.value)) {
  //   console.error('usersTable.value 必须是数组');
  //   return;
  // }
  // 过滤用户列表
  filteredUsersTable.value = usersTable.value.filter(user => {
    // 匹配姓名、电话、时间范围，如果未输入电话，则默认匹配
    const matchName = !name || user.name.includes(name);
    const phonePattern = phone.split('').map(char => `(${char})`).join('.*?');
    const matchPhone = !phone || new RegExp(phonePattern).test(user.phone);
    const matchTime = !start || !end || (
        new Date(user.createTime) >= new Date(start) &&
        new Date(user.createTime) <= new Date(end)
    );
    return matchName && matchPhone && matchTime;
  });
  // 重置分页器
  currentPage.value = 1;
};

// 重置表单
const resetForm = () => {
  searchForm.value = {
    name: '',
    phone: '',
  }
  timeRanges.value = []
  filteredUsersTable.value = usersTable.value // 重置过滤后的用户数据
  currentPage.value = 1 // 重置分页器当前页
}

// 获取全部用户列表
const getUsersList = async () => {
  const res = await reqUserPages()
  if (res.data.code === '000000') {
    usersTable.value = res.data.data.records
    total.value = res.data.data.total
    filteredUsersTable.value = usersTable.value // 初始时显示所有用户
  }
  // console.log(filteredUsersTable.value)
}

// 分页相关
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)
const onPageSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  getUsersList();
}
const onCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  getUsersList();
}

// 状态切换
const onStatusChange = async (status, id) => {
  const action = status === 'ENABLE' ? reqEnableUserStatus : reqDisableUserStatus // 切换状态的请求方法
  const successMsg = status === 'ENABLE' ? '启用成功!' : '禁用成功!'
  const failMsg = status === 'ENABLE' ? '启用失败!' : '禁用失败!'
  const res = await action(id)
  if (res.data.code === '000000') {
    ElMessage.success(successMsg)
  } else {
    ElMessage.error(failMsg)
  }
}

// 分配角色
const  allocRole = ref(null)
const handlerAllocRole = (user) => {
  allocRole.value.showAndInit(user.id);
}

</script>

<style scoped>

.el-form-item {
  margin-right: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 30%;
}

</style>